local ads__shiheng = fk.CreateSkill {
  name = "ads__shiheng",
}

ads__shiheng:addEffect("active", {
  anim_type = "drawcard",
  prompt = "#ads__shiheng-active",
  max_phase_use_time = 1,
  target_num = 0,
  on_use = function(self, room, effect)
    local from = effect.from
    local pile_num = #room.draw_pile
    local choices = {}
    for i = 0, pile_num do
      table.insert(choices, tostring(i))
    end
    local choice = room:askToChoice(from, {
      choices = choices,
      skill_name = ads__shiheng.name,
      prompt = "请选择要摸的牌数（0-" .. pile_num .. "）",
    })
    local draw_count = tonumber(choice)
    if draw_count and draw_count > 0 then
      from:drawCards(draw_count, ads__shiheng.name)
      if from:isAlive() then
        room:askToDiscard(from, {
          min_num = draw_count,
          max_num = draw_count,
          skill_name = ads__shiheng.name,
          include_equip = false,
          cancelable = false,
        })
    end
    end
  end,
})


ads__shiheng:addAI({
  think = function(self, ai)
    local player = ai.player
    local handcards = player:getCardIds("h")
    local handcard_num = #handcards
    if handcard_num == 0 then
      return "", 0
    end
    local cards = ai:getEnabledCards(".|.|.|hand|.|.|.")
    local low_value_cards = ai:getChoiceCardsByKeepValue(cards, #cards, function(value) 
      return value < 45 
    end)
    local replaceable_count = #low_value_cards
    local pile_num = #ai.room.draw_pile
    local draw_count = 0
    if replaceable_count > 0 then
      draw_count = math.min(replaceable_count, handcard_num, pile_num, 50)  
      if replaceable_count <= 2 then
        draw_count = math.min(replaceable_count, pile_num, 3)
      elseif replaceable_count >= 3 then
        draw_count = math.min(replaceable_count, pile_num, 5)
      end
    end
    
    if draw_count <= 0 then
      return "", 0
    end
    
    local benefit = ai:getBenefitOfEvents(function(logic)
      logic:drawCards(player, draw_count, self.skill.name)
      local cards_to_discard = ai:getChoiceCardsByKeepValue(handcards, draw_count, function(value) 
        return value < 45 
      end)
      if #cards_to_discard > 0 then
        logic:throwCard(cards_to_discard, self.skill.name, player, player)
      end
    end)
    
    if benefit > 0 then
      return tostring(draw_count), benefit
    else
      return "", 0
    end
  end,
})

Fk:loadTranslationTable{
  ["$ads__shiheng1"] = "容我三思。",
  ["$ads__shiheng2"] = "且慢。",
  ["ads__shiheng"] = "失衡",
  [":ads__shiheng"] = "出牌阶段限一次，你可以摸任意张牌，然后弃置等量的牌。",
  ["#ads__shiheng-active"] = "发动 失衡，摸任意张牌，然后弃置等量的牌",
}

return ads__shiheng